package com.warm.androidstudy.common;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import com.warm.androidstudy.MyApplication;
import com.warm.androidstudy.R;
import com.warm.androidstudy.utils.AndroidWorkaround;
import com.warm.androidstudy.utils.LogUtil;
import com.warm.androidstudy.utils.StatusBarUtil;
import com.warm.androidstudy.widget.CustomProgressDialog;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 集成基础Activity
 * @author DELL
 * @param <VM>
 * @param <VDB>
 */
public abstract class BaseActivity <VM extends BaseViewModel,VDB extends ViewDataBinding> extends AppCompatActivity {
    /**
     * 获取布局
     * @return
     */
    protected abstract int getLayoutId();
    /**
     * 初始化
     */
    protected abstract void init();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 初始化布局
     */
    protected abstract void initView();

//    /**
//     * onCreate中的监听初始化
//     */
//    protected abstract void initListener();

    /**
     * viewModel
     */
    protected VM mViewModel;
    /**
     * dataBind绑定数据
     */
    protected VDB binding;

    protected CustomProgressDialog progressDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCustomDensity(this, MyApplication.getInstance());
        setContentView(getLayoutId());
        //初始化databind
        binding = DataBindingUtil.setContentView(this,getLayoutId());
        binding.setLifecycleOwner(this);
        initViewModel();
        init();
        initView();
        //注意：这个颜色不要改；需要自己的颜色请重写 getMyCustomStatusBarColor
        setStatusBarTextColorWhite(getMyCustomStatusBarColor());
        setImmerseLayout();
        initData();
//        initListener();
    }

    /**
     * 初始化ViewModel
     */
    public void initViewModel(){
        if (mViewModel==null){
            Class modelClass;
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType){
                modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
            }else {
                //若是没有指定泛型参数，则默认使用BaseViewModel
                modelClass = BaseViewModel.class;
            }
            mViewModel = (VM) new ViewModelProvider(this).get(modelClass);
        }
    }

    public void initProgressDialog() {
        if (null == progressDialog) {
            progressDialog = new CustomProgressDialog(this, "加载中...", R.drawable.customprogress_dialog_anim);
            ColorDrawable colorDrawable = new ColorDrawable(Color.argb(0, 0, 0, 0));
            progressDialog.getWindow().setBackgroundDrawable(colorDrawable);
        }
    }

    public void showProgressDialog() {
        if (null == progressDialog) {
            initProgressDialog();
        }
        if (!progressDialog.isShowing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        progressDialog.show();
                    } catch (Exception e) {
                        LogUtil.e(e.getMessage());
                    }
                }
            });
        }
    }

    public void dismissProgressDialog() {
        if (null != progressDialog && progressDialog.isShowing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        progressDialog.dismiss();
                    } catch (Exception e) {
                        LogUtil.e(e.getMessage());
                    }
                }
            });
        }
    }


    /**
     * 设置状态栏的字体颜色为深色
     */
    protected void setStatusBarTextColorWhite(int color) {
        setStatusBarView(color);
    }


    /**
     * 设置状态栏的颜色，目前只是在4.4以上有效
     */
    protected void setStatusBarView(int color) {
        com.jaeger.library.StatusBarUtil.setColor(this, color,0);
    }


    /**
     * 设置沉浸式透明状态栏（4.4以上）
     */
    protected void setImmerseLayout() {
        StatusBarUtil.transparencyBar(this);
        //兼容底部虚拟导航栏，比如华为 -- 需要在setContentView()方法后面执行
        if (AndroidWorkaround.checkDeviceHasNavigationBar(this)) {
            //适配华为手机虚拟键遮挡tab的问题
            AndroidWorkaround.assistActivity(findViewById(android.R.id.content));
        }
    }

    protected int getMyCustomStatusBarColor(){
        return ContextCompat.getColor(this,R.color.gray_9b);
    }

    /**
     * 设置状态栏的字体颜色为深色
     */
    protected void setStatusBarTextColorBlack() {
        setStatusBarView(R.color.colorPrimary);
        int type = StatusBarUtil.StatusBarLightMode(this);
        //改成不区分类型
        StatusBarUtil.StatusBarLightMode(this, 3);
    }

    /**
     * 设置状态栏的字体颜色为浅色
     */
    protected void setStatusBarTextColorWhite() {
        setStatusBarView(R.color.colorPrimary);
        int type = StatusBarUtil.StatusBarDarkMode(this);
        //改成不区分类型
        StatusBarUtil.StatusBarDarkMode(this, 3);
        setImmerseLayout();
    }

    /**
     * 设置底部布局随着底部虚拟导航栏动态变化调整
     */
    protected void setBottomBar() {
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }

    /**
     * 避免被底部虚拟菜单遮挡了页面内容（如华为）
     */
    public void setAutoBottomView() {
        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.BLACK);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    /**
     * 此方法只是关闭软键盘
     * @param context
     */
    public void hintKbTwo(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && getCurrentFocus() != null) {
            if (getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }


    /**
     * 屏幕适配
     * 设计图宽360dp
     */
    private static float sNoncompatDensity;
    private static float sNoncompatScaledDensity;
    private static void setCustomDensity(@NonNull Activity activity, @NonNull final Application application) {
        DisplayMetrics appDisplayMetrics = application.getResources().getDisplayMetrics();
        if (sNoncompatDensity == 0) {
            sNoncompatDensity = appDisplayMetrics.density;
            sNoncompatScaledDensity = appDisplayMetrics.scaledDensity;
            application.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    if (newConfig != null && newConfig.fontScale > 0) {
                        sNoncompatScaledDensity = application.getResources().getDisplayMetrics().scaledDensity;
                    }
                }

                @Override
                public void onLowMemory() {

                }
            });
        }
        float targetDensity = appDisplayMetrics.widthPixels / 360;
        float targetScaledDensity = targetDensity * (sNoncompatScaledDensity / sNoncompatDensity);
        int targetDensityDpi = (int) (160 * targetDensity);

        appDisplayMetrics.density = targetDensity;
        appDisplayMetrics.scaledDensity = targetScaledDensity;
        appDisplayMetrics.densityDpi = targetDensityDpi;

        DisplayMetrics activityDisplayMetrics = activity.getResources().getDisplayMetrics();
        activityDisplayMetrics.density = targetDensity;
        activityDisplayMetrics.scaledDensity = targetScaledDensity;
        activityDisplayMetrics.densityDpi = targetDensityDpi;
    }
}
